package com.itheima.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.pojo.Result;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.util.AppJwtUtil;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        try {
            // 获取请求参数
            Map<String, String[]> map = request.getParameterMap();
            User u = new User();
            BeanUtils.populate(u,map);
            UserService service = new UserService();
            User user = service.login(u);
            System.out.println("登录后的用户信息: "+user);
            // 判断登录结果
            if (user==null){ // 登录失败
                //response.getWriter().print(0);
                Result result = new Result(false,"用户名或密码错误",null);
                BaseController.responseJson(response,result);
            }else {
                // 登录成功
                // 保存登录成功的状态到session
                //request.getSession().setAttribute("user",user);
                //response.getWriter().print(1);
                // 封装响应结果对象,并返回给浏览器
                //Result result = new Result(true,"登录成功",null);
                //BaseController.responseJson(response,result);
                // 登录成功后,生成token并返回给浏览器
                // 将用户信息保存到redis中,redis的键为id的值
                String token = AppJwtUtil.getToken(user.getId());
                System.out.println("登录成功后,生成的token值: "+token);
                BaseController.responseJson(response,new Result(true,"登录成功！", token));
            }

        } catch (Exception e) {
            e.printStackTrace();
            Result result = new Result(false,"服务器忙...",null);
            BaseController.responseJson(response,result);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}